<?php

namespace catchAdmin\pc\model;

use catcher\exceptions\AlertErrorException;
use catcher\Tree;

class SysVocation extends \catchAdmin\model\SysVocation
{

    public $name = 'sys_vocation';


    /**
     * 保存
     */
    public function saveData($param)
    {
        $level = 1;
        if (!empty($param['parent_id'])) {
            $parent_msg = $this
                ->where('id', $param['parent_id'])
                ->find();
            if (empty($parent_msg)) {
                throw new AlertErrorException('上级不存在');
            }
            $level = $parent_msg['level'] + 1;
        }

        $this->startTrans();

        $msg = $this->saveDataCC([
            'id'            => $param['id'] ?? 0,
            'parent_id'     => $param['parent_id'],
            'level'         => $level,
            'vocation_name' => $param['vocation_name'],
        ]);

        if ($this
                ->where('level', $msg['level'])
                ->where('vocation_name', $msg['vocation_name'])
                ->count() > 1) {
            throw new AlertErrorException('同级名称不能重复');
        }

        $this->commit();

        return $msg;
    }


    /**
     * 审核
     */
    public function audit($param)
    {
        $msg = $this
            ->where('id', $param['id'])
            ->where('status', 1)
            ->find();

        if (empty($msg)) {
            throw new AlertErrorException();
        }

        $msg->status = $param['status'];
        $msg->save();

        return $msg;
    }


    /**
     * 删除
     */
    public function deleteData($param)
    {
        return $this->deleteBy($param['id']);
    }


    ########################### 显示 #####################

    public function indexData($param)
    {
        $app = $this
            ->with(['parent']);

        return $this->indexDataPcCC($param, $app);
    }


    /**
     * 一二级分类
     */
    public function index12($param)
    {
        $list = $this
            ->whereIn('level', [1, 2])
            ->where('status', 2)
            ->select()
            ->toArray();

        return Tree::done($list);
    }


    public function index3($param)
    {
        $app = $this
            ->where('level', 3)
            ->where('parent_id', $param['parent_id']);

        return [
            'cus' => (clone $app)
                ->where('sys_is', 2)
                ->select()
                ->toArray(),
            'sys' => (clone $app)
                ->where('sys_is', 1)
                ->select()
                ->toArray(),
        ];
    }


    public function indexByPid($param)
    {
        if (empty($param['parent_id'])) {
            $param['parent_id'] = 0;
        }

        $app = $this->where('parent_id', $param['parent_id']);
        $param['limit'] = 999;

        return $this->indexDataPcCC($param, $app);
    }


}
